package cn.harry.cabinet.theme.manager

import android.content.Context
import android.content.res.ColorStateList
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageButton
import androidx.core.content.ContextCompat
import cn.harry.cabinet.theme.constants.ThemeConstants

/**
 * 按钮主题管理器 - 重构版本
 * 专门负责管理应用中所有按钮的主题切换和样式调整
 * 
 * 特性：
 * - 智能按钮类型识别
 * - 支持多种按钮样式
 * - 批量主题更新
 * - 动画主题切换
 */
object ButtonThemeManager {
    
    /**
     * 按钮类型定义
     */
    enum class ButtonType {
        PRIMARY,        // 主要按钮 (填充背景)
        SECONDARY,      // 次要按钮 (边框按钮)
        ICON_BUTTON,    // 图标按钮
        CARD_BUTTON     // 卡片按钮
    }
    
    /**
     * 按钮主题配色方案
     */
    data class ButtonThemeColors(
        // 主要按钮颜色
        val primaryButtonBackground: Int,
        val primaryButtonText: Int,
        val primaryButtonDisabled: Int,
        
        // 次要按钮颜色
        val secondaryButtonBorder: Int,
        val secondaryButtonText: Int,
        val secondaryButtonBackground: Int,
        
        // 图标按钮颜色
        val iconButtonTint: Int,
        val iconButtonBackground: Int,
        
        // 卡片按钮颜色
        val cardButtonBackground: Int,
        val cardButtonText: Int
    )
    
    /**
     * 获取主题的按钮配色方案
     */
    fun getButtonThemeColors(theme: ThemeManager.Theme, @Suppress("UNUSED_PARAMETER") _context: Context): ButtonThemeColors {
        return when (theme) {
            ThemeManager.Theme.CHINA_RED -> ButtonThemeColors(
                primaryButtonBackground = ThemeConstants.ChinaRedColors.primaryButtonDrawable,
                primaryButtonText = ThemeConstants.CommonColors.white,
                primaryButtonDisabled = ThemeConstants.CommonColors.gray,
                
                secondaryButtonBorder = ThemeConstants.ChinaRedColors.primaryColorRes,
                secondaryButtonText = ThemeConstants.ChinaRedColors.primaryColorRes,
                secondaryButtonBackground = ThemeConstants.ChinaRedColors.secondaryButtonDrawable,
                
                iconButtonTint = ThemeConstants.ChinaRedColors.primaryColorRes,
                iconButtonBackground = ThemeConstants.CommonColors.transparent,
                
                cardButtonBackground = ThemeConstants.ChinaRedColors.secondaryColorRes,
                cardButtonText = ThemeConstants.CommonColors.white
            )
            
            ThemeManager.Theme.VIBRANT_ORANGE -> ButtonThemeColors(
                primaryButtonBackground = ThemeConstants.VibrantOrangeColors.primaryButtonDrawable,
                primaryButtonText = ThemeConstants.CommonColors.white,
                primaryButtonDisabled = ThemeConstants.CommonColors.gray,
                
                secondaryButtonBorder = ThemeConstants.VibrantOrangeColors.primaryColorRes,
                secondaryButtonText = ThemeConstants.VibrantOrangeColors.primaryColorRes,
                secondaryButtonBackground = ThemeConstants.VibrantOrangeColors.secondaryButtonDrawable,
                
                iconButtonTint = ThemeConstants.VibrantOrangeColors.primaryColorRes,
                iconButtonBackground = ThemeConstants.CommonColors.transparent,
                
                cardButtonBackground = ThemeConstants.VibrantOrangeColors.secondaryColorRes,
                cardButtonText = ThemeConstants.CommonColors.white
            )
            
            ThemeManager.Theme.TECH_BLUE -> ButtonThemeColors(
                primaryButtonBackground = ThemeConstants.TechBlueColors.primaryButtonDrawable,
                primaryButtonText = ThemeConstants.CommonColors.white,
                primaryButtonDisabled = ThemeConstants.CommonColors.gray,
                
                secondaryButtonBorder = ThemeConstants.TechBlueColors.primaryColorRes,
                secondaryButtonText = ThemeConstants.TechBlueColors.primaryColorRes,
                secondaryButtonBackground = ThemeConstants.TechBlueColors.secondaryButtonDrawable,
                
                iconButtonTint = ThemeConstants.TechBlueColors.primaryColorRes,
                iconButtonBackground = ThemeConstants.CommonColors.transparent,
                
                cardButtonBackground = ThemeConstants.TechBlueColors.secondaryColorRes,
                cardButtonText = ThemeConstants.CommonColors.white
            )
        }
    }
    
    /**
     * 应用按钮主题到单个按钮
     */
    fun applyButtonTheme(
        button: Button, 
        theme: ThemeManager.Theme, 
        buttonType: ButtonType = ButtonType.PRIMARY,
        context: Context
    ) {
        try {
            val colors = getButtonThemeColors(theme, context)
            
            when (buttonType) {
                ButtonType.PRIMARY -> {
                    // 主要按钮样式
                    val drawable = ContextCompat.getDrawable(context, colors.primaryButtonBackground)
                    drawable?.mutate() // 确保drawable是独立的副本
                    button.background = drawable
                    button.setTextColor(ContextCompat.getColor(context, colors.primaryButtonText))
                }
                
                ButtonType.SECONDARY -> {
                    // 次要按钮样式
                    val drawable = ContextCompat.getDrawable(context, colors.secondaryButtonBackground)
                    drawable?.mutate() // 确保drawable是独立的副本
                    button.background = drawable
                    button.setTextColor(ContextCompat.getColor(context, colors.secondaryButtonText))
                }
                
                ButtonType.CARD_BUTTON -> {
                    // 卡片按钮样式
                    button.setBackgroundColor(ContextCompat.getColor(context, colors.cardButtonBackground))
                    button.setTextColor(ContextCompat.getColor(context, colors.cardButtonText))
                }
                
                else -> {
                    // 默认使用主要按钮样式
                    val drawable = ContextCompat.getDrawable(context, colors.primaryButtonBackground)
                    drawable?.mutate() // 确保drawable是独立的副本
                    button.background = drawable
                    button.setTextColor(ContextCompat.getColor(context, colors.primaryButtonText))
                }
            }
        } catch (e: Exception) {
            android.util.Log.w(ThemeConstants.LogTags.BUTTON_THEME_MANAGER, 
                "Failed to apply button theme: ${e.message}")
        }
    }
    
    /**
     * 应用图标按钮主题
     */
    fun applyImageButtonTheme(
        imageButton: ImageButton,
        theme: ThemeManager.Theme,
        context: Context
    ) {
        try {
            val colors = getButtonThemeColors(theme, context)
            
            // 设置图标颜色
            imageButton.imageTintList = ColorStateList.valueOf(
                ContextCompat.getColor(context, colors.iconButtonTint)
            )
            
            // 设置背景
            imageButton.setBackgroundColor(
                ContextCompat.getColor(context, colors.iconButtonBackground)
            )

        } catch (e: Exception) {
            android.util.Log.w(ThemeConstants.LogTags.BUTTON_THEME_MANAGER, 
                "Failed to apply ImageButton theme: ${e.message}")
        }
    }
    
    /**
     * 智能检测按钮类型
     */
    private fun detectButtonType(button: Button, @Suppress("UNUSED_PARAMETER") _context: Context): ButtonType {
        // 首先通过 tag 识别（优先级最高，来自样式定义）
        val tag = button.tag?.toString()
        if (tag != null) {
            return when {
                tag.contains("button_primary", ignoreCase = true) -> ButtonType.PRIMARY
                tag.contains("button_secondary", ignoreCase = true) -> ButtonType.SECONDARY
                tag.contains("button_card", ignoreCase = true) -> ButtonType.CARD_BUTTON
                tag.contains("button_icon", ignoreCase = true) -> ButtonType.ICON_BUTTON
                else -> ButtonType.PRIMARY
            }
        }
        
        // 其次通过ID精确匹配
        return when (button.id) {
            in ThemeConstants.ButtonIds.primaryButtonIds -> ButtonType.PRIMARY
            in ThemeConstants.ButtonIds.secondaryButtonIds -> ButtonType.SECONDARY
            
            // 根据按钮文字内容智能判断
            else -> {
                val text = button.text.toString().lowercase()
                when {
                    ThemeConstants.ButtonKeywords.primaryKeywords.any { text.contains(it) } -> 
                        ButtonType.PRIMARY
                    ThemeConstants.ButtonKeywords.secondaryKeywords.any { text.contains(it) } -> 
                        ButtonType.SECONDARY
                    else -> ButtonType.PRIMARY
                }
            }
        }
    }
    
    /**
     * 递归更新ViewGroup中所有按钮的主题
     */
    fun updateAllButtonsInView(
        view: View,
        theme: ThemeManager.Theme,
        context: Context
    ) {
        when (view) {
            is ViewGroup -> {
                // 递归处理所有子视图
                for (i in 0 until view.childCount) {
                    updateAllButtonsInView(view.getChildAt(i), theme, context)
                }
            }
            
            is Button -> {
                // 检查是否使用了传统的固定颜色背景
                if (isLegacyButtonBackground(view)) {
                    applyLegacyButtonTheme(view, theme, context)
                } else {
                    val buttonType = detectButtonType(view, context)
                    applyButtonTheme(view, theme, buttonType, context)
                }
            }
            
            is ImageButton -> {
                applyImageButtonTheme(view, theme, context)
            }
        }
    }
    
    /**
     * 检查按钮是否使用传统的固定颜色背景
     */
    private fun isLegacyButtonBackground(button: Button): Boolean {
        // 检查按钮是否使用了传统的背景drawable
        val resourceName = try {
            button.context.resources.getResourceEntryName(button.id)
        } catch (e: Exception) {
            ""
        }
        
        // 如果按钮使用了特定的传统背景drawable，则需要特殊处理
        val text = button.text.toString().lowercase()
        return text.contains("取消") || text.contains("cancel") ||
               text.contains("确认") || text.contains("confirm") ||
               text.contains("保存") || text.contains("save") ||
               resourceName.contains("cancel") || resourceName.contains("confirm")
    }
    
    /**
     * 为使用传统背景的按钮应用主题
     */
    private fun applyLegacyButtonTheme(button: Button, theme: ThemeManager.Theme, context: Context) {
        try {
            val colors = getButtonThemeColors(theme, context)
            
            // 根据按钮文字判断类型并应用相应的主题化背景
            val text = button.text.toString().lowercase()
            
            when {
                text.contains("取消") || text.contains("cancel") -> {
                    // 取消按钮使用次要按钮样式
                    val drawable = ContextCompat.getDrawable(context, colors.secondaryButtonBackground)
                    drawable?.mutate() // 确保drawable是独立的副本
                    button.background = drawable
                    button.setTextColor(ContextCompat.getColor(context, colors.secondaryButtonText))
                }
                text.contains("删除") || text.contains("delete") -> {
                    // 删除按钮保持红色
                    // 不修改，保持原来的红色样式
                }
                else -> {
                     // 强制重新加载drawable，避免缓存问题
                    val drawable = ContextCompat.getDrawable(context, colors.primaryButtonBackground)
                    drawable?.mutate() // 确保drawable是独立的副本
                    button.background = drawable
                    button.setTextColor(ContextCompat.getColor(context, colors.primaryButtonText))
                }
            }
        } catch (e: Exception) {
            android.util.Log.w(ThemeConstants.LogTags.BUTTON_THEME_MANAGER, 
                "Failed to apply legacy button theme: ${e.message}")
        }
    }
    
    /**
     * 创建主题化的按钮样式
     */
    fun createThemedButton(
        context: Context,
        text: String,
        theme: ThemeManager.Theme,
        buttonType: ButtonType = ButtonType.PRIMARY
    ): Button {
        val button = Button(context)
        button.text = text
        applyButtonTheme(button, theme, buttonType, context)
        return button
    }
    
    /**
     * 为按钮添加主题切换动画
     */
    fun animateButtonThemeChange(
        button: Button,
        fromTheme: ThemeManager.Theme,
        toTheme: ThemeManager.Theme,
        context: Context,
        duration: Long = ThemeConstants.Defaults.THEME_ANIMATION_DURATION
    ) {
        try {
            // 创建属性动画
            val animator = android.animation.ValueAnimator.ofFloat(0f, 1f)
            animator.duration = duration
            
            animator.addUpdateListener { animation ->
                val fraction = animation.animatedValue as Float
                
                // 在这里可以添加颜色渐变动画
                // 目前先直接应用新主题
                if (fraction >= 0.5f) {
                    applyButtonTheme(button, toTheme, detectButtonType(button, context), context)
                }
            }
            
            animator.start()

        } catch (e: Exception) {
            // 如果动画失败，直接应用新主题
            applyButtonTheme(button, toTheme, detectButtonType(button, context), context)
            android.util.Log.w(ThemeConstants.LogTags.BUTTON_THEME_MANAGER, 
                "Animation failed, applied theme directly: ${e.message}")
        }
    }
    
    /**
     * 批量更新指定类型的按钮
     */
    fun updateButtonsByType(
        view: View,
        theme: ThemeManager.Theme,
        buttonType: ButtonType,
        context: Context
    ) {
        when (view) {
            is ViewGroup -> {
                for (i in 0 until view.childCount) {
                    updateButtonsByType(view.getChildAt(i), theme, buttonType, context)
                }
            }
            is Button -> {
                if (detectButtonType(view, context) == buttonType) {
                    applyButtonTheme(view, theme, buttonType, context)
                }
            }
        }
    }
}